package com.cyp.livelog.web;

import com.cyp.livelog.bean.Article;
import com.cyp.livelog.utils.DbUtils;
import com.mysql.jdbc.StringUtils;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 日月星辰
 * @date 2020/12/15 21:26
 * @description
 */
@WebServlet(value = {"/", "/home"})
public class HomeAction extends HttpServlet {

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.setCharacterEncoding("utf-8");
    String action = req.getParameter("a");
    if (StringUtils.isNullOrEmpty(action)) {
      index(req, resp);
    } else if (action.equals("search")) {
      search(req, resp);
    }
  }

  private void search(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String search = req.getParameter("search");
    req.setAttribute("search", search);
    ResultSet res = DbUtils.query("select id,title,create_time,update_time from article where title like '%" + search + "%'");
    try {
      res.next();
      List<Article> list = new ArrayList<>();
      if (res.getString(2) != null) {
        Article a = new Article();
        a.setId(res.getInt(1));
        a.setTitle(res.getString(2));
        a.setCreateTime(res.getDate(4) != null ? res.getDate(4) : res.getDate(3));
        list.add(a);
      }
      req.setAttribute("list", list);
    } catch (SQLException e) {
    }
    req.getRequestDispatcher("/WEB-INF/article/search.jsp").forward(req, resp);
  }

  private void index(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //获取最新的文章
    try {
      ResultSet articles = DbUtils.query("select id,title,create_time from article order by id desc limit 10");
      List<Article> list = new ArrayList<>();
      while (articles.next()) {
        Article article = new Article();
        article.setId(articles.getInt(1));
        article.setTitle(articles.getString(2));
        article.setCreateTime(articles.getDate(3));
        list.add(article);
      }
      req.setAttribute("list", list);

      ResultSet res = DbUtils.query("select count(*) from article");
      res.next();
      req.setAttribute("count", res.getInt(1));
    } catch (
        SQLException e) {
      e.printStackTrace();
    }
    req.getRequestDispatcher("/index.jsp").forward(req, resp);
  }
}
